import * as React from "react";
import * as ReactDOM from "react-dom";
import { loaderJsFile } from "x-site-util";
import "../styles/share-dialog.less";
import GaUtil from "common-util/ga-util";
import ExpireLock from "expire-lock";

declare let window: any;
declare let ZeroClipboard: any;
declare let QRCode: any;

export default class ShareDialog extends React.Component<any, any> {
  constructor(props) {
    super(props);
    this.state = {};
  }

  static defaultProps = {
    qrcodeurl: ""
  };

  componentDidMount() {
    let target = this;
    (async () => {
      if (!window.ZeroClipboard) {
        await loaderJsFile(
          "//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/javascripts/zp/ZeroClipboard.js"
        );
      }
      if (!window.QRCode) {
        await loaderJsFile(
          "//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/javascripts/qrcode.min.js"
        );
      }
      target._dealQrcode();
    })();
  }

  componentDidUpdate(prevProps) {
    if (this.props.qrcodeurl != prevProps.qrcodeurl) {
      this._dealQrcode();
    }
  }

  render() {
    return (
      <div className="shareArea clipboardA">
        <a
          className="sharePopularize"
          onClick={this._show.bind(this)}
          href="javascript:void(0);"
        >
          分享推广&nbsp;
        </a>
        <div className="shareDialog">
          <div ref="qrcode" className="qrcode" />
          <p>
            扫一扫,或<a
              id="qrcodeLink"
              ref="qrcodeLink"
              style={{ cursor: "pointer" }}
              onClick={this._download}
            >
              下载二维码
            </a>
          </p>
          <div className="link">
            链接:{" "}
            <input
              style={{ height: "19px" }}
              onMouseOver={this._showCopy}
              type="text"
              value={this.props.qrcodeurl}
            />
            <a
              data-clipboard-text={this.props.qrcodeurl}
              className="copyBtn"
              ref="copyBtn"
            >
              单击复制
              <div className="qrcodeDownArrow" />
            </a>
            <div className="copySuccess" ref="copySuccess">
              <img src="//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/images/copy_success.png" />复制成功!
            </div>
          </div>
          <div className="share">
            分享:{" "}
            <img
              onClick={this.shareByWeibo}
              src="//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/images/xinlang.png"
            />
          </div>
          <div className="qrcodeRightArrow" />
        </div>
      </div>
    );
  }

  _dealQrcode = () => {
    this._bindClipboard();
    window.onclick = function(e) {
      if (
        !$(e.target).hasClass("sharePopularize") &&
        !$(e.target).hasClass("shareDialog") &&
        $(e.target).parents(".shareDialog").length == 0
      ) {
        $(".shareDialog").hide();
      }
    };
    this._showQrcode();
  };

  _bindClipboard = async () => {
    // if (!window.ZeroClipboard) {
    //     await loaderJsFile('//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/javascripts/zp/ZeroClipboard.js')
    // }

    let flag = true;
    if (flag && $("a[data-clipboard-text]").length > 0) {
      let client = [];
      $("a[data-clipboard-text]").each((k, v) => {
        client[k] = new ZeroClipboard($("a[data-clipboard-text]")[k]); //初始化复制粘贴 要用dom节点
        client[k].on("ready", function(readyEvent) {
          client[k].on("aftercopy", function(event) {
            if (event.data["text/plain"] != "") {
              $($("a[data-clipboard-text]")[k]).hide();
              $($("a[data-clipboard-text]")[k]).next().show();
              setTimeout(function() {
                $($("a[data-clipboard-text]")[k]).next().hide();
              }, 3000);
            } else {
              console.error("复制失败");
            }
          });
        });
      });
      flag = false;
    }
  };

  /**
     * 鼠标移到地址上,出现单击复制按钮
     */
  _showCopy = () => {
    let thisBtn = $(ReactDOM.findDOMNode(this.refs.copyBtn));
    thisBtn.show();
    setTimeout(function() {
      thisBtn.hide();
    }, 5000);
  };

  _showQrcode = () => {
    // if (!window.QRCode) {
    //     await loaderJsFile("//qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/javascripts/qrcode.min.js");
    // }
    let qrcodeurl = this.props.qrcodeurl || "http://www.qianmi.com";
    //二维码图片链接
    // let siteIconImgSrc = this.props.platform == 'app' ? this.props.jumpUrl.getIn(['app', 'data', 'logoUrl']) : this.props.globalSetup.get("siteIconImgSrc");
    $(ReactDOM.findDOMNode(this.refs.qrcode)).empty();
    // this.props.globalSetup.get("siteIconImgSrc") && $("#qrcode").append('<div id="codeico"></div>');  //二维码 ICON展示区域
    new QRCode(ReactDOM.findDOMNode(this.refs.qrcode), {
      text: qrcodeurl,
      width: 150,
      height: 150,
      colorDark: "#000000",
      colorLight: "#ffffff"
    });
    // if (siteIconImgSrc) {
    //     let size = Math.ceil($("#code_img").height() * 0.15); //设置icon大小
    //     let margin = ($("#code_img").height() - size) / 2;  //设置二维码icon居中
    //
    //     let temcss = {
    //         'margin': margin,
    //         'width': size + 'px',
    //         'height': size + 'px',
    //         'position': 'absolute',
    //         'zIndex': '9999999',
    //         'background': 'url(' + siteIconImgSrc + ') no-repeat',
    //         'backgroundSize': (size + 'px ' + size + 'px'),
    //         'border': '2px solid #fff'
    //     };
    //     $("#codeico").css(temcss);
    // }
  };

  shareByWeibo = () => {
    let f = "http://v.t.sina.com.cn/share/share.php?",
      e = encodeURIComponent,
      s = screen,
      picUrl =
        "http://web-img.qmimg.com/x-site/public/images/demo2/logo.png@185w_60h_1wh.png",
      title = "我的分享",
      url = this.props.qrcodeurl,
      p = [
        "url=",
        e(url),
        "&title=",
        e(title),
        "&pic=",
        e(picUrl),
        "&appkey=4144218247"
      ].join("");
    if (
      !window.open(
        [f, p].join(""),
        "mb",
        [
          "toolbar=0,status=0,resizable=1,width=620,height=450,left=",
          (s.width - 620) / 2,
          ",top=",
          (s.height - 450) / 2
        ].join("")
      )
    )
      url.href = [f, p].join("");
  };

  _download = () => {
    let fileName = "download.png",
      title = this.props.qrcodeurl,
      qrcodeLinkDom = $(ReactDOM.findDOMNode(this.refs.qrcodeLink));
    try {
      fileName = title.split("/")[title.split("/").length - 1] + ".png";
    } catch (err) {
      throw "文件名截取失败" + err;
    }
    qrcodeLinkDom.attr("download", fileName);
    qrcodeLinkDom.attr("href", $(".qrcode img").attr("src"));
  };

  @ExpireLock()
  _show() {
    $(".shareDialog").hide();
    $(ReactDOM.findDOMNode(this)).find(".shareDialog").show();
    let pageInfo = this.props.pageInfo || {};
    GaUtil.addPageEvent({
      eventAction: "分享推广",
      eventLabel: pageInfo.tplCode || "",
      platform: this.props.platform
    });
  }
}
